package com.campus.secondhand.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.concurrent.TimeUnit;

import com.campus.secondhand.entity.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.secondhand.common.Result;
import com.campus.secondhand.mapper.ConversationMapper;
import com.campus.secondhand.mapper.MessageMapper;
import com.campus.secondhand.mapper.ProductMapper;
import com.campus.secondhand.mapper.PurchaseRequestMapper;
import com.campus.secondhand.model.dto.MessageSendDTO;
import com.campus.secondhand.model.dto.ProductMessageDTO;
import com.campus.secondhand.model.dto.PurchaseRequestMessageDTO;
import com.campus.secondhand.model.vo.ConversationVO;
import com.campus.secondhand.model.vo.MessageVO;
import com.campus.secondhand.model.vo.ProductDetailVO;
import com.campus.secondhand.service.MessageService;
import com.campus.secondhand.service.ProductService;
import com.campus.secondhand.service.PurchaseRequestService;
import com.campus.secondhand.service.UserService;
import com.campus.secondhand.service.SchoolService;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;

/**
 * 消息服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Messages> implements MessageService {

    private final MessageMapper messageMapper;
    private final ConversationMapper conversationMapper;
    private final ProductMapper productMapper;
    private final PurchaseRequestMapper purchaseRequestMapper;
    private final UserService userService;
    @Lazy
    private final ProductService productService;
    private final SchoolService schoolService;
    private final RedisTemplate<String, Object> redisTemplate;

    // Redis缓存键常量
    private static final String CACHE_CONVERSATION_PREFIX = "conversation:";
    private static final String CACHE_CONVERSATION_LIST = "conversation:list:";
    private static final String CACHE_MESSAGE_PREFIX = "message:";
    private static final String CACHE_MESSAGE_CONVERSATION = "message:conversation:";
    private static final long CACHE_CONVERSATION_EXPIRE = 10; // 会话缓存过期时间，单位分钟
    private static final long CACHE_MESSAGE_EXPIRE = 5; // 消息缓存过期时间，单位分钟

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<MessageVO> sendMessage(Long senderId, MessageSendDTO messageSendDTO) {
        // 校验发送者
        User sender = userService.getUserById(senderId);
        if (sender == null) {
            return Result.error(404, "发送者不存在");
        }

        // 校验接收者
        User receiver = userService.getUserById(messageSendDTO.getReceiverId());
        if (receiver == null) {
            return Result.error(404, "接收者不存在");
        }

        // 不能给自己发消息
        if (senderId.equals(messageSendDTO.getReceiverId())) {
            return Result.error(400, "不能给自己发消息");
        }

        // 创建消息实体
        Messages messages = new Messages();
        messages.setSenderId(senderId);
        messages.setReceiverId(messageSendDTO.getReceiverId());
        messages.setContent(messageSendDTO.getContent());
        messages.setIsRead(0); // 未读
        messages.setCreatedAt(LocalDateTime.now());

        // 商品相关数据
        Product product = null;
        // 如果有商品ID，验证商品是否存在
        if (messageSendDTO.getProductId() != null) {
            product = productMapper.selectById(messageSendDTO.getProductId());
            if (product == null) {
                return Result.error(404, "关联商品不存在");
            }
            messages.setProductId(messageSendDTO.getProductId());
        }

        // 求购信息相关数据
        PurchaseRequest purchaseRequest = null;
        // 如果有求购信息ID，验证求购信息是否存在
        if (messageSendDTO.getRequestId() != null) {
            purchaseRequest = purchaseRequestMapper.selectById(messageSendDTO.getRequestId());
            if (purchaseRequest == null) {
                return Result.error(404, "关联求购信息不存在");
            }
            messages.setPurchaseRequestId(messageSendDTO.getRequestId());
        }

        // 保存消息
        this.save(messages);

        // 查找或创建会话
        Conversations conversations = conversationMapper.findConversationBetweenUsers(senderId,
                messageSendDTO.getReceiverId());
        if (conversations == null) {
            // 创建新会话
            conversations = new Conversations();
            conversations.setUserAId(senderId);
            conversations.setUserBId(messageSendDTO.getReceiverId());
            conversations.setLastMessage(messages.getContent());
            conversations.setUserAUnreadCount(0);
            conversations.setUserBUnreadCount(1); // 接收者未读+1
            conversations.setCreatedAt(LocalDateTime.now());
            conversations.setUpdatedAt(LocalDateTime.now());
            conversationMapper.insert(conversations);
        } else {
            // 更新现有会话
            conversations.setLastMessage(messages.getContent());
            conversations.setUpdatedAt(LocalDateTime.now());

            // 增加接收者未读消息数
            if (conversations.getUserAId().equals(messageSendDTO.getReceiverId())) {
                conversations.setUserAUnreadCount(conversations.getUserAUnreadCount() + 1);
            } else {
                conversations.setUserBUnreadCount(conversations.getUserBUnreadCount() + 1);
            }

            // 更新会话
            conversationMapper.updateById(conversations);
        }

        // 转换为VO并返回，传入商品和求购信息对象以便设置详细信息
        MessageVO messageVO = convertToMessageVOWithDetails(messages, sender, receiver, product, purchaseRequest);
        messageVO.setIsSelf(true);

        // 清除相关缓存
        clearConversationCache(senderId, messageSendDTO.getReceiverId());
        clearMessageCache(senderId, messageSendDTO.getReceiverId());

        return Result.success(messageVO);
    }

    @Override
    public Result<List<ConversationVO>> getUserConversationsPaged(Long userId, Integer page, Integer pageSize) {
        // 校验用户
        User user = userService.getUserById(userId);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }

        // 构建缓存Key
        String cacheKey = CACHE_CONVERSATION_LIST + userId;

        // 尝试从缓存获取
        Object cachedConversations = redisTemplate.opsForValue().get(cacheKey);
        if (cachedConversations != null) {
            return Result.success((List<ConversationVO>) cachedConversations, "获取成功(缓存)");
        }

        // 计算分页偏移量
        int offset = (page - 1) * pageSize;

        // 获取用户的分页会话列表
        List<Conversations> conversations = conversationMapper.findUserConversationsPaged(userId, offset, pageSize);
        if (conversations.isEmpty()) {
            return Result.success(new ArrayList<>());
        }

        // 转换为VO
        List<ConversationVO> conversationVOs = conversations.stream()
                .map(conversation -> {
                    ConversationVO vo = new ConversationVO();
                    vo.setId(conversation.getId());

                    // 获取对方用户信息
                    Long targetUserId = conversation.getUserAId().equals(userId)
                            ? conversation.getUserBId()
                            : conversation.getUserAId();
                    User targetUser = userService.getUserById(targetUserId);

                    if (targetUser != null) {
                        vo.setUserId(targetUserId);
                        // 优先使用昵称，昵称为空时使用用户名
                        vo.setUsername(targetUser.getNickname() != null && !targetUser.getNickname().isEmpty()
                                ? targetUser.getNickname()
                                : targetUser.getUsername());
                        vo.setAvatar(targetUser.getAvatar());

                        // 添加用户学校信息
                        if (targetUser.getSchoolId() != null) {
                            vo.setSchool(schoolService.getSchoolById(targetUser.getSchoolId())
                                    .getData().getName());
                        }

                        // 添加用户电话
                        vo.setPhone(targetUser.getPhone());

                        // 添加用户地区
                        vo.setRegion(targetUser.getRegion());

                        // 添加用户自我介绍
                        vo.setIntroduction(targetUser.getIntroduction());

                    } else {
                        // 用户不存在时设置默认值
                        vo.setUserId(targetUserId);
                        vo.setUsername("未知用户");
                        vo.setAvatar("/static/default-avatar.png");
                    }

                    // 添加会话最后消息
                    vo.setLastMessage(conversation.getLastMessage());
                    vo.setUpdatedAt(conversation.getUpdatedAt());

                    // 添加未读消息数
                    if (conversation.getUserAId().equals(userId)) {
                        vo.setUnreadCount(conversation.getUserAUnreadCount());
                    } else {
                        vo.setUnreadCount(conversation.getUserBUnreadCount());
                    }

                    return vo;
                })
                .collect(Collectors.toList());

        // 写入缓存，短暂时间
        redisTemplate.opsForValue().set(cacheKey, conversationVOs, CACHE_CONVERSATION_EXPIRE, TimeUnit.MINUTES);

        return Result.success(conversationVOs);
    }

    @Override
    public Result<List<MessageVO>> getConversationMessages(Long userId, Long targetUserId) {
        // 构建缓存Key
        String cacheKey = CACHE_MESSAGE_CONVERSATION + userId + ":" + targetUserId;

        // 尝试从缓存获取
        Object cachedMessages = redisTemplate.opsForValue().get(cacheKey);
        if (cachedMessages != null) {
            return Result.success((List<MessageVO>) cachedMessages, "获取成功(缓存)");
        }

        // 校验用户
        User user = userService.getUserById(userId);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }

        // 校验目标用户
        User targetUser = userService.getUserById(targetUserId);
        if (targetUser == null) {
            return Result.error(404, "目标用户不存在");
        }

        // 获取二者之间的所有消息
        List<Messages> messagesList = messageMapper.findMessagesBetweenUsers(userId, targetUserId);

        // 将消息标记为已读
        markMessagesAsRead(targetUserId, userId);

        // 转换为VO
        List<MessageVO> messageVOs = convertToMessageVOList(messagesList, userId);

        // 写入缓存
        redisTemplate.opsForValue().set(cacheKey, messageVOs, CACHE_MESSAGE_EXPIRE, TimeUnit.MINUTES);

        return Result.success(messageVOs);
    }

    @Override
    public Result<List<MessageVO>> getConversationMessagesForProduct(Long userId, Long targetUserId, Long productId) {
        // 校验用户
        User user = userService.getUserById(userId);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }

        // 校验目标用户
        User targetUser = userService.getUserById(targetUserId);
        if (targetUser == null) {
            return Result.error(404, "目标用户不存在");
        }

        // 校验商品
        Product product = productMapper.selectById(productId);
        if (product == null) {
            return Result.error(404, "商品不存在");
        }

        // 构建缓存Key
        String cacheKey = CACHE_MESSAGE_CONVERSATION + userId + ":" + targetUserId + ":product:" + productId;

        // 尝试从缓存获取
        Object cachedMessages = redisTemplate.opsForValue().get(cacheKey);
        if (cachedMessages != null) {
            return Result.success((List<MessageVO>) cachedMessages, "获取成功(缓存)");
        }

        // 获取二者之间关于特定商品的消息
        List<Messages> messagesList = messageMapper.findMessagesBetweenUsersForProduct(userId, targetUserId, productId);

        // 将消息标记为已读
        markMessagesAsRead(targetUserId, userId);

        // 转换为VO
        List<MessageVO> messageVOs = convertToMessageVOList(messagesList, userId);

        // 写入缓存
        redisTemplate.opsForValue().set(cacheKey, messageVOs, CACHE_MESSAGE_EXPIRE, TimeUnit.MINUTES);

        return Result.success(messageVOs);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> markConversationAsRead(Long userId, Long targetUserId) {
        // 获取会话
        Conversations conversation = conversationMapper.findConversationBetweenUsers(userId, targetUserId);
        if (conversation == null) {
            return Result.error(404, "会话不存在");
        }

        // 更新未读数为0
        if (conversation.getUserAId().equals(userId)) {
            conversation.setUserAUnreadCount(0);
        } else {
            conversation.setUserBUnreadCount(0);
        }

        // 更新会话
        conversationMapper.updateById(conversation);

        // 将消息标记为已读
        markMessagesAsRead(targetUserId, userId);

        return Result.success(null, "已标记为已读");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> deleteConversation(Long userId, Long targetUserId) {
        // 获取会话
        Conversations conversation = conversationMapper.findConversationBetweenUsers(userId, targetUserId);
        if (conversation == null) {
            return Result.error(404, "会话不存在");
        }

        // 删除消息
        messageMapper.deleteMessagesBetweenUsers(userId, targetUserId);

        // 删除会话
        conversationMapper.deleteById(conversation.getId());

        // 清除相关缓存
        clearConversationCache(userId, targetUserId);
        clearMessageCache(userId, targetUserId);

        return Result.success(null, "删除成功");
    }

    @Override
    public Result<List<MessageVO>> getChatMessages(Long userId, Long conversationId, Integer page, Integer pageSize) {
        // 构建缓存Key
        String cacheKey = CACHE_MESSAGE_PREFIX + "chat:" + userId ;

        // 尝试从缓存获取
        Object cachedMessages = redisTemplate.opsForValue().get(cacheKey);
        if (cachedMessages != null) {
            return Result.success((List<MessageVO>) cachedMessages, "获取成功(缓存)");
        }

        // 校验用户
        User user = userService.getUserById(userId);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }

        // 校验会话是否存在
        Conversations conversations = conversationMapper.selectById(conversationId);
        if (conversations == null) {
            return Result.error(404, "会话不存在");
        }

        // 验证用户是否属于该会话
        if (!conversations.getUserAId().equals(userId) && !conversations.getUserBId().equals(userId)) {
            return Result.error(403, "无权访问该会话");
        }

        // 计算分页偏移量
        int offset = (page - 1) * pageSize;

        // 获取消息列表
        List<Messages> messages = messageMapper.findMessagesByConversationId(conversationId, offset, pageSize);

        // 获取对方用户ID
        Long targetUserId = conversations.getUserAId().equals(userId) ? conversations.getUserBId()
                : conversations.getUserAId();

        // 标记消息为已读
        markMessagesAsRead(targetUserId, userId);

        // 更新会话的未读计数
        if (conversations.getUserAId().equals(userId)) {
            conversations.setUserAUnreadCount(0);
        } else {
            conversations.setUserBUnreadCount(0);
        }
        conversationMapper.updateById(conversations);

        // 转换为VO
        List<MessageVO> messageVOs = convertToMessageVOList(messages, userId);

        // 写入缓存
        redisTemplate.opsForValue().set(cacheKey, messageVOs, CACHE_MESSAGE_EXPIRE, TimeUnit.MINUTES);

        return Result.success(messageVOs);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> markConversationMessagesAsRead(Long userId, Long conversationId) {
        // 校验用户
        User user = userService.getUserById(userId);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }

        // 校验会话是否存在
        Conversations conversations = conversationMapper.selectById(conversationId);
        if (conversations == null) {
            return Result.error(404, "会话不存在");
        }

        // 验证用户是否属于该会话
        if (!conversations.getUserAId().equals(userId) && !conversations.getUserBId().equals(userId)) {
            return Result.error(403, "无权访问该会话");
        }

        // 获取对方用户ID
        Long targetUserId = conversations.getUserAId().equals(userId) ? conversations.getUserBId()
                : conversations.getUserAId();

        // 标记消息为已读
        markMessagesAsRead(targetUserId, userId);

        // 更新会话的未读计数
        if (conversations.getUserAId().equals(userId)) {
            conversations.setUserAUnreadCount(0);
        } else {
            conversations.setUserBUnreadCount(0);
        }
        conversationMapper.updateById(conversations);

        return Result.success(null, "标记已读成功");
    }

    @Override
    public Result<ConversationVO> createConversation(Long userId, Long partnerId) {
        // 构建缓存Key
        String cacheKey = CACHE_CONVERSATION_PREFIX + userId + ":" + partnerId;

        // 尝试从缓存获取
        Object cachedConversation = redisTemplate.opsForValue().get(cacheKey);
        if (cachedConversation != null) {
            return Result.success((ConversationVO) cachedConversation, "获取成功(缓存)");
        }

        // 校验用户
        User user = userService.getUserById(userId);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }

        // 校验对话方
        User partner = userService.getUserById(partnerId);
        if (partner == null) {
            return Result.error(404, "对话方用户不存在");
        }

        // 不能和自己创建会话
        if (userId.equals(partnerId)) {
            return Result.error(400, "不能与自己创建会话");
        }

        // 先查找是否已存在会话
        Conversations existingConversations = conversationMapper.findConversationBetweenUsers(userId, partnerId);
        if (existingConversations != null) {
            ConversationVO vo = new ConversationVO();
            vo.setId(existingConversations.getId());
            vo.setUserId(partnerId);
            vo.setUsername(partner.getUsername());
            vo.setAvatar(partner.getAvatar());

            // 添加用户学校信息
            if (partner.getSchoolId() != null) {
                vo.setSchool(schoolService.getSchoolById(partner.getSchoolId())
                        .getData().getName());
            }

            // 添加用户电话
            vo.setPhone(partner.getPhone());

            // 添加用户地区
            vo.setRegion(partner.getRegion());

            // 添加用户自我介绍
            vo.setIntroduction(partner.getIntroduction());

            vo.setLastMessage(existingConversations.getLastMessage());

            // 设置未读消息数
            if (existingConversations.getUserAId().equals(userId)) {
                vo.setUnreadCount(existingConversations.getUserAUnreadCount());
            } else {
                vo.setUnreadCount(existingConversations.getUserBUnreadCount());
            }

            vo.setUpdatedAt(existingConversations.getUpdatedAt());

            // 写入缓存
            redisTemplate.opsForValue().set(cacheKey, vo, CACHE_CONVERSATION_EXPIRE, TimeUnit.MINUTES);

            return Result.success(vo);
        }

        // 创建新会话
        Conversations conversations = new Conversations();
        conversations.setUserAId(userId);
        conversations.setUserBId(partnerId);
        conversations.setUserAUnreadCount(0);
        conversations.setUserBUnreadCount(0);
        conversations.setCreatedAt(LocalDateTime.now());
        conversations.setUpdatedAt(LocalDateTime.now());
        conversations.setLastMessage("还没有任何消息，快来打个招呼吧");

        conversationMapper.insert(conversations);

        // 转换为VO
        ConversationVO vo = new ConversationVO();
        vo.setId(conversations.getId());
        vo.setUserId(partnerId);
        vo.setUsername(partner.getUsername());
        vo.setAvatar(partner.getAvatar());

        // 添加用户学校信息
        if (partner.getSchoolId() != null) {
            vo.setSchool(schoolService.getSchoolById(partner.getSchoolId())
                    .getData().getName());
        }

        // 添加用户电话
        vo.setPhone(partner.getPhone());

        // 添加用户地区
        vo.setRegion(partner.getRegion());

        // 添加用户自我介绍
        vo.setIntroduction(partner.getIntroduction());

        vo.setLastMessage(conversations.getLastMessage());
        vo.setUnreadCount(0);
        vo.setUpdatedAt(conversations.getUpdatedAt());

        // 写入缓存
        redisTemplate.opsForValue().set(cacheKey, vo, CACHE_CONVERSATION_EXPIRE, TimeUnit.MINUTES);

        return Result.success(vo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> deleteConversationById(Long userId, Long conversationId) {
        // 校验用户
        User user = userService.getUserById(userId);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }

        // 查找会话
        Conversations conversations = conversationMapper.selectById(conversationId);
        if (conversations == null) {
            return Result.error(404, "会话不存在");
        }

        // 验证用户是否属于该会话
        if (!conversations.getUserAId().equals(userId) && !conversations.getUserBId().equals(userId)) {
            return Result.error(403, "您不是该会话的参与者");
        }

        // 获取对方用户ID
        Long targetUserId = conversations.getUserAId().equals(userId) ? conversations.getUserBId()
                : conversations.getUserAId();

        // 删除会话
        conversationMapper.deleteById(conversationId);

        // 删除该会话的所有消息
        messageMapper.deleteMessagesBetweenUsers(userId, targetUserId);

        // 清除相关缓存
        clearConversationCache(userId, targetUserId);
        clearMessageCache(userId, targetUserId);

        return Result.success(null, "删除成功");
    }

    /**
     * 清除会话相关缓存
     */
    private void clearConversationCache(Long userA, Long userB) {
        // 清除会话列表缓存
        redisTemplate.delete(CACHE_MESSAGE_PREFIX + "chat:" + userA );
        redisTemplate.delete(CACHE_MESSAGE_PREFIX + "chat:"+ userB);
        // 清除会话详情缓存
        redisTemplate.delete(CACHE_CONVERSATION_PREFIX + userA + ":" + userB);
        redisTemplate.delete(CACHE_CONVERSATION_PREFIX + userB + ":" + userA);
    }

    /**
     * 清除消息相关缓存
     */
    private void clearMessageCache(Long userA, Long userB) {
        // 清除会话消息缓存
        redisTemplate.delete(CACHE_MESSAGE_CONVERSATION + userA + ":" + userB);
        redisTemplate.delete(CACHE_MESSAGE_CONVERSATION + userB + ":" + userA);
    }

    /**
     * 将消息标记为已读
     */
    private void markMessagesAsRead(Long senderId, Long receiverId) {
        messageMapper.markMessagesAsRead(senderId, receiverId);
    }

    /**
     * 转换消息列表为VO列表
     */
    private List<MessageVO> convertToMessageVOList(List<Messages> messages, Long currentUserId) {
        if (messages.isEmpty()) {
            return new ArrayList<>();
        }

        return messages.stream().map(message -> {
            // 获取发送者信息
            User sender = userService.getUserById(message.getSenderId());

            // 获取接收者信息
            User receiver = userService.getUserById(message.getReceiverId());

            // 获取商品信息（如果有）
            Product product = null;
            if (message.getProductId() != null) {
                product = productMapper.selectById(message.getProductId());
            }

            // 获取求购信息（如果有）
            PurchaseRequest purchaseRequest = null;
            if (message.getPurchaseRequestId() != null) {
                purchaseRequest = purchaseRequestMapper.selectById(message.getPurchaseRequestId());
            }

            MessageVO vo = convertToMessageVOWithDetails(message, sender, receiver, product, purchaseRequest);

            // 判断是否是自己发送的消息
            vo.setIsSelf(message.getSenderId().equals(currentUserId));

            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 转换消息实体为VO
     */
    private MessageVO convertToMessageVO(Messages messages, User sender, User receiver, Product product) {
        // 调用详细版本的方法，第二个参数为null
        PurchaseRequest purchaseRequest = null;
        if (messages.getPurchaseRequestId() != null) {
            purchaseRequest = purchaseRequestMapper.selectById(messages.getPurchaseRequestId());
        }
        return convertToMessageVOWithDetails(messages, sender, receiver, product, purchaseRequest);
    }

    /**
     * 转换消息实体为VO，并传入商品和求购信息对象以便设置详细信息
     */
    private MessageVO convertToMessageVOWithDetails(Messages messages, User sender, User receiver, Product product,
            PurchaseRequest purchaseRequest) {
        MessageVO vo = new MessageVO();
        vo.setId(messages.getId());
        vo.setSenderId(messages.getSenderId());
        vo.setReceiverId(messages.getReceiverId());

        // 发送者信息
        if (sender != null) {
            vo.setSenderName(sender.getUsername());
            vo.setSenderAvatar(sender.getAvatar());
        }

        // 商品信息
        if (messages.getProductId() != null) {
            vo.setProductId(messages.getProductId());

            if (product != null) {
                vo.setProductName(product.getName());
                vo.setProductPrice(product.getPrice()); // 设置商品价格

                // 获取商品详情来获取图片
                Result<ProductDetailVO> productDetailResult = productService.getProductDetail(product.getId(),
                        messages.getSenderId());
                if (productDetailResult.getCode() == 200 && productDetailResult.getData() != null &&
                        productDetailResult.getData().getImageUrls() != null &&
                        !productDetailResult.getData().getImageUrls().isEmpty()) {
                    // 设置商品主图和缩略图
                    vo.setProductImage(productDetailResult.getData().getImageUrls().get(0));
                } else {
                    // 设置默认图片
                    vo.setProductImage("/static/default-product.png");
                }
            }
        }

        // 求购信息
        if (messages.getPurchaseRequestId() != null) {
            vo.setPurchaseRequestId(messages.getPurchaseRequestId());

            // 获取求购信息详情
            if (purchaseRequest != null) {
                vo.setPurchaseRequestName(purchaseRequest.getTitle());
                vo.setPurchaseRequestBudget(purchaseRequest.getBudget()); // 设置求购意向价格/预算
            }
        }

        vo.setContent(messages.getContent());
        vo.setIsRead(messages.getIsRead() == 1);
        vo.setCreatedAt(messages.getCreatedAt());

        return vo;
    }
}